<template>
  <div class="MyCards h-full min-h-0 flex-col flex-1">
    <MyQueryForm
      ref="$queryForm"
      :query-schemas="querySchemas"
      :query-format="queryFormat"
      :padding-x="paddingX"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #handle>
        <slot name="handle"></slot>
      </template>
    </MyQueryForm>
    <n-spin :show="loading" class="relative min-h-0 flex-1">
      <n-scrollbar ref="$scroll" @scroll="onScroll">
        <div
          class="cardList"
          :style="{
            gridTemplateColumns: `repeat(${col}, 1fr)`,
            gap,
            padding: `0 ${paddingX} ${paddingY}`,
          }"
        >
          <template v-for="(item, index) in listData" :key="index">
            <slot name="card" v-bind="item"></slot>
          </template>
        </div>
        <template v-if="!loading && !listData.length">
          <div
            v-if="!slots.empty"
            class="pos-absolute wh-full flex-col items-center justify-center"
          >
            <img :src="appStore.nodataImg" />
            <div
              :class="['text-14 font-400', appStore.isDeep ? 'color-#FFFFFFCC' : 'color-#817E92']"
            >
              暂无数据
            </div>
          </div>
          <slot name="empty"></slot>
        </template>
      </n-scrollbar>
    </n-spin>
  </div>
</template>

<script setup lang="jsx">
import { useAppStore } from '@/store'
defineOptions({ name: 'MyCards' })
const slots = useSlots()
const props = defineProps({
  /**
   * @remote true: 后端分页  false： 前端分页
   */
  remote: {
    type: Boolean,
    default: true,
  },
  /**
   * @remote 是否分页
   */
  isPagination: {
    type: Boolean,
    default: true,
  },
  getData: {
    type: Function,
    required: true,
  },
  autoLoad: {
    type: Boolean,
    default: true,
  },
  queryFormat: {
    type: Function,
    default: null,
  },
  querySchemas: {
    type: Array,
    default: () => [],
  },
  col: {
    type: Number,
    default: 3,
  },
  gap: {
    type: String,
    default: '16px',
  },
  paddingX: {
    type: String,
    default: '24px',
  },
  paddingY: {
    type: String,
    default: '24px',
  },
})
const emit = defineEmits(['onDataChange', 'onReset'])
const appStore = useAppStore()
// 对查询项表单的处理
// const { queryItems, initQueryItems, getQueryParams } = useSchema(
//   props.querySchemas,
//   props.queryFormat
// )
const $queryForm = ref(null)
const $scroll = ref(null)
const loading = ref(false)
const listData = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 15,
  pages: 0,
  total: 0,
})
// 监听滚动
function onScroll(e) {
  const dom = e.target
  const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight
  if (scrollDistance == 0) {
    console.log('ReachBottom')
    handleReachBottom()
  }
}
// 滚动触底加载
function handleReachBottom() {
  if (pagination.page <= pagination.pages - 1 && !loading.value) {
    pagination.page++
    handleQuery()
  }
}

/**
 *  依据现有条件查询
 */
async function handleQuery() {
  try {
    loading.value = true
    // 分页相关参数
    let paginationParams = {}
    // 如果非分页模式或者使用前端分页,则无需传分页参数
    if (props.isPagination && props.remote) {
      paginationParams = { current: pagination.page, size: pagination.pageSize }
    }
    // 查询项表单参数
    const otherParams = $queryForm.value.getQueryParams()
    const { data } = await props.getData({
      ...otherParams,
      ...paginationParams,
    })
    if (props.isPagination && props.remote) {
      // 第一页赋值，其他的拼接在后面
      listData.value =
        pagination.page === 1 ? data?.records || [] : listData.value.concat(data?.records || [])
    } else {
      listData.value = data || []
    }
    pagination.pages = Number(data?.pages || 0)
    pagination.total = Number(data?.total || 0)
  } catch (error) {
    listData.value = []
    pagination.itemCount = 0
  } finally {
    emit('onDataChange', listData.value)
    loading.value = false
  }
}

/**
 *  依据现有条件，重新从第一页查询
 */
function handleSearch() {
  pagination.page = 1
  $scroll.value.scrollTo({ top: 0 })
  handleQuery()
}

/**
 *  重置查询条件，并从第一页查询
 */
async function handleReset() {
  $queryForm.value.initQueryItems()
  nextTick(() => {
    emit('onReset')
    handleSearch()
  })
}

onMounted(() => {
  // 等待可能加载的默认查询项
  $queryForm.value.initQueryItems()
  // 自动请求
  props.autoLoad && handleQuery()
})

defineExpose({
  // 不重置查询项，从当前页查
  handleQuery,
  // 不重置查询项，从第1页查
  handleSearch,
  // 重置查询项，从第1页查
  handleReset,
})
</script>
<style lang="scss" scoped>
.MyCards {
  .cardList {
    display: grid;
  }
}
</style>
